const path = require('path')
const del = require('del')
const webpack = require('webpack')
const packager = require('electron-packager')

const { parseArgs, info, error, done, DEFAULT_TARGETS, makeConfig, compileCallback } = require('./util')

const args = parseArgs(process.argv.slice(2))

// 可接受参数
const env = process.env.NODE_ENV || 'production'
const platform = args[ 'platform' ] || null
const arch = args[ 'arch' ] || null

// 清理文件夹
function clean () {
  del.sync([ 'dist/*' ])
  info('delete folder dist/* \n')
}

function buildRenderer () {
  return new Promise(function (resolve, reject) {
    const config = makeConfig(DEFAULT_TARGETS.renderer, env, require('./config/webpack.base.vue.config'))
    webpack(config, compileCallback(resolve, reject))
  }).then(out => info(out + '\n')).catch(err => {
    error(err + '\n')
    throw new Error()
  })
}

function buildMain () {
  return new Promise(function (resolve, reject) {
    const config = makeConfig(DEFAULT_TARGETS.main, env)
    webpack(config, compileCallback(resolve, reject))
  }).then(out => info(out + '\n')).catch(err => {
    error(err + '\n')
    throw new Error()
  })
}

function packageElectron () {
  // packager 配置信息
  const packagerConfig = {
    dir: path.join(__dirname, '../'),
    // icon: path.join(__dirname, '../build/icons/icon'),
    ignore: /(^\/(src|test|\.[a-z]+|README|yarn|static|buildscript|tsconfig|tslint))|\.gitkeep/,
    out: path.join(__dirname, '../build'),
    overwrite: true
  }

  if (platform) {
    packagerConfig.platform = platform
  }
  if (arch) {
    packagerConfig.arch = arch
  }
  packager(packagerConfig)
    .then(appPaths => {
      done('packager electron app at:' + appPaths + '\n')
    })
    .catch(err => {
      error(err + '\n')
      throw new Error()
    })
}

function build () {
  clean()
  Promise.all([ buildRenderer(), buildMain() ]).then(() => packageElectron()).catch((e) => { error(e) })
}

build()
